﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataBase.Utils;
using GreenXi.Model;
using GreenXi.Pages.Power;
using Prism.Commands;
using DataBase;
using Gateway = DataBase.Gateway;
using System.Windows;

namespace GreenXi.ViewModel
{
    public class GatewayViewModel : RegionModel
    {
        private Pages.Power.GatewayEdit gatewayEdit;
        public GatewayViewModel() {
            using MyDbContext myDbContext = new();
            GatewayList = new(myDbContext.GetGateway());

            SaveColumn = new DelegateCommand<object>((p) => { SaveColumn_Click(p); });//保存栏目
            CloseWindows = new DelegateCommand<object>((p) => { CloseWindows_Click(); });//关闭编辑窗口


            DelProject = new DelegateCommand<object>((p) => { DelProject_Click(p); });//删除项目
            AddProject = new DelegateCommand(() => { AddProject_Click(); });          //新增项目
            EditProject = new DelegateCommand<object>((p) => { EditProject_Click(p); });//编辑项目
            SaveProject = new DelegateCommand<object>((p) => { SaveProject_Click(p); });//保存项目
        }

        #region 项目
        private void EditProject_Click(Object param)
        {
            var paramss = param as Gateway;
            Gateway = paramss;
            gatewayEdit = new();
            gatewayEdit.DataContext = this;
            gatewayEdit.ShowDialog();
        }

        // Swap 方法用于交换数组中两个位置的对象
        void Swap(List<Gateway> array, int index1, int index2)
        {
            if (array == null)
            {
                return;
            }
            int tmpId = array[index1].Id;
            array[index1].Id = array[index2].Id;
            array[index2].Id = tmpId;
        }

        private void SaveProject_Click(Object param)
        {
            using MyDbContext myDbContext = new();
            myDbContext.UpdateRegion(Regions);
        }
        private async void AddProject_Click()
        {
            var region = new Gateway
            {
                Name = "网关名称"
            };
            GatewayList.Add(region);
            using MyDbContext myDbContext = new();
            await myDbContext.AddAsync<DataBase.Gateway>(region);

        }
        private async void DelProject_Click(object param)//删除项目
        {
            var paramss = param as Gateway;
            using MyDbContext myDbContext = new();
            await myDbContext.DeleteAsync<Gateway>(paramss);
            GatewayList.Remove(paramss);
        }
        #endregion

        private void SaveColumn_Click(Object param)
        {
            using MyDbContext myDbContext = new();
            myDbContext.UpdateGateway(Gateway);
            MessageBox.Show("修改成功！");
            gatewayEdit.Close();//关闭弹窗
        }
        private void CloseWindows_Click()
        {
            gatewayEdit.Close();//关闭弹窗
        }
    }
}
